package com.qf.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.BiIntFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.blog.dto.IndexPostDto;
import com.qf.blog.dto.MyPage;
import com.qf.blog.entity.User;
import com.qf.blog.service.IPostService;
import com.qf.blog.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class IndexController {

    @Value("${blog.login.auto}")
    private boolean autuLogin;

    @Value("${blog.login.id}")
    private Integer userId;

    @Autowired
    private IUserService userService;

    @Autowired
    private IPostService postService;

    // 用户只要访问/就会进入这个方法
    @GetMapping("/")
    public String index(HttpSession session, Model model,
                        MyPage<IndexPostDto> page,
                        @RequestParam(defaultValue = "1") Integer orderMode) {
        // 1.判断用户是否已经登录了
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            autoLogin(); // 实现自动登录
        }

        // 2.查询帖子数据
        page = postService.indexPostData(page,orderMode);
        page.setPath("/"); // 设置切面切换时发送的请求地址

        // 3.把查询的出来的数据保存在Model中
        model.addAttribute("page", page);

        return "index";
    }

    public void autoLogin() {
        if (autuLogin) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpSession session = requestAttributes.getRequest().getSession();
            // 自动登录
            User user = userService.getById(userId);
            user.setPassword(null);
            session.setAttribute("loginUser", user);
        }
    }
}
